package com.taotao.order.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserLoginService;

public class LoginInterceptor implements HandlerInterceptor{
	@Value("${COOKIE_TOKEN_KEY}")
	private String COOKIE_TOKEN_KEY;
	@Value("${SSO_LOGIN_URL}")
	private String SSO_LOGIN_URL;
	@Autowired
	private UserLoginService userLoginService;
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView)
			throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		//获取cookie中的token
		String token = CookieUtils.getCookieValue(request, COOKIE_TOKEN_KEY);
		if (StringUtils.isBlank(token)) {
			//获取当前的路径
			String url = request.getRequestURL().toString();
			//token值为空,用户未登陆,跳回到登陆界面http://localhost:8088/page/showLogin
			response.sendRedirect(SSO_LOGIN_URL+"/page/showLogin?redirectUrl="+url);
			return false;
		}
		//token不为空,查询redis中的登陆信息
		TaotaoResult result = userLoginService.getUserByToken(token);
		if (result.getStatus() != 200) {
			//redis中的登陆信息已过期
			//获取当前的路径
			String url = request.getRequestURL().toString();
			//token值为空,用户未登陆,跳回到登陆界面http://localhost:8088/page/showLogin
			response.sendRedirect(SSO_LOGIN_URL+"/page/showLogin?redirectUrl="+url);
			return false;
		}
		//查询得到用户信息
		TbUser user = (TbUser) result.getData();
		//将用户信息存入到域中
		request.setAttribute("user", user);
		return true;
	}

}
